const APIError = require('../rest').APIError;
const util = require('../others/util');

var products = [{
        name: 'iPhone',
        price: 6999
    },
    {
        name: 'Kindle',
        price: 999
    }
];

var getUsers = async(ctx, next) => {
    // just for test
    // ctx.session.user = {user: 'xxcao'}; 
    await global.sequelize.query('SELECT * FROM user', {
            type: sequelize.QueryTypes.SELECT
        })
        .then(function (results) {
            console.log(results);
            var resObject = util.AssembleJson(200, '获取成功', results);
            ctx.rest(resObject);
        })
        .catch(function (err) {
            console.log(err);
            throw new APIError('user:not found', 'user not found by id.');
        });
};

var getProducts = async(ctx, next) => {
    ctx.rest({
        products: products
    });
};

var addProducts = async(ctx, next) => {
    var p = {
        name: ctx.request.body.name,
        price: ctx.request.body.price
    };
    if (p) {
        products.push(p);
        ctx.rest(p);
    } else {
        throw new APIError('product:not found', 'product not found by id.');
    }
};

module.exports = {
    'GET /api/products': getProducts,
    'POST /api/products': addProducts,
    'GET /api/users': getUsers
};